package tool.model;

import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import tool.antlr4.CLexer;
import tool.antlr4.CParser;
import tool.cfgvisitors.CCfgVisitor;
import tool.model.cfg.EntryNode;
import tool.utils.CharStreamUtils;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 生成CFG
 */
public class CfgGenerator {

    public HashMap<String, ArrayList<EntryNode>> generateCCfg(String fileName) {
        System.out.println("================C->CFG===================");

        //C语言词法分析器
        CLexer lexer = new CLexer(CharStreamUtils.getStream(fileName));
        
        //获得词法分析器输出流
        CommonTokenStream tokens = new CommonTokenStream(lexer);
       
        //C语言语法分析器
        CParser parser = new CParser(tokens);
        
        //创建AST
        ParseTree tree = parser.compilationUnit();
        
        //跟踪器
        CCfgVisitor visitor = new CCfgVisitor(fileName);

        //遍历并生成CFG
        ParseTreeWalker parseTreeWalker = new ParseTreeWalker();
        parseTreeWalker.walk(visitor, tree);

        return visitor.getCFGs();
    }
}
